package ru.positron;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class Utils {
	
	public static InputStream download(String url) throws IOException {
		return download(new URL(url), 30);
	}
	
	public static InputStream download(URL url) throws IOException {
		return download(url, 30);
	}
	
	public static InputStream download(URL url, int timeout) throws IOException {   	
    	URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
    	HTTPRequest dlReq = new HTTPRequest(url, HTTPMethod.GET, FetchOptions.Builder.withDeadline(timeout) );
    	return new ByteArrayInputStream( fetcher.fetch(dlReq).getContent() );
	}
	
	public static class ResponseResult {
		InputStream content;
		String header;
	}
	public static ResponseResult downloadAndHeader(URL url, String header) throws IOException {
		return downloadAndHeader(url, 30, header);
	}
	public static ResponseResult downloadAndHeader(URL url, int timeout, String header) throws IOException {
    	URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
    	HTTPRequest dlReq = new HTTPRequest(url, HTTPMethod.GET, FetchOptions.Builder.withDeadline(timeout) );
    	HTTPResponse resp = fetcher.fetch(dlReq);
    	ResponseResult res = new ResponseResult();    	
    	header = header.toLowerCase();
    	for (HTTPHeader hh : resp.getHeaders()) {
			if (header.equals(hh.getName().toLowerCase()))
				res.header = hh.getValue();
		}
    	res.content = new ByteArrayInputStream (resp.getContent() );
    	return res;
	}

}
